<?php

namespace app\admin\quick\actions;


use quick\admin\actions\Action;
use quick\admin\annotation\AdminAuth;
use quick\admin\components\Component;
use quick\admin\form\Form;
use quick\admin\library\cloud\CloudException;
use quick\admin\library\cloud\CloudNoLoginException;
use quick\admin\library\service\PluginService;
use think\Request;

/**
 * 安装本地插件
 * @AdminAuth(title="安装本地插件",auth=true,menu=true,login=true)
 * @package app\admin\resource\example\actions
 */
class PluginOfflineInstallAction extends Action
{

    /**
     * 模型主键
     *
     * @var string
     */
    public static $pk = "name";

    /**
     * 关联模型
     *
     * @var string
     */
    protected static $model = 'app\common\model\SystemPlugin';


    protected function initAction()
    {
        $this->display(Component::button($this->name())->type('primary'));
        $this->dialog();

    }


    /**
     * 动作提交数据接口
     *
     * @return mixed
     * @throws \quick\admin\Exception
     * @throws \think\Exception
     */
    public function store()
    {
        try {

            PluginService::instance()->offlineInstall($this->request->file('file'));
            $response = $this->response()->success('success')->message('安装成功')
                ->event('admin_menu',[],200,true);

        } catch (CloudNoLoginException $e) {

            return  $this->response()->error($e->getMessage());

        } catch (CloudException $e) {

            return  $this->response()->error($e->getMessage());

        } catch (\Exception $e) {
            $response = $this->response()->error($e->getMessage() ,[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
        return $response;
    }


    protected function form()
    {
        $form = Form::make();

        $form->upload('path', '安装包')
            ->uploadUrl('/admin.php'.$this->storeUrl())->file(['zip'])->fillUsing(function ($inputs, $model){
            return $inputs['path']['url'];
        })->rules('require|max:500');

        return $form;
    }


    /**
     * 动作异步数据接口
     * @return mixed
     * @throws \quick\admin\Exception
     * @throws \think\Exception
     */
    public function load()
    {
        if (!$this->handleCanRun($this->request, [])) {
            quick_abort(500, '你无权访问');
        }
        $form = $this->form();
        $form->url($this->storeUrl());
        $form->resolve([]);
        $form->hideReset();
        return $this->response()->success("success", $form);
    }




}
